<template>
  <view class="app-layout">
    <app-header title="库存调整" />
    <view class="app-main">
      <view class="goods-container">
        <view class="goods-title">
          <text>批量设置：</text>
          <view class="goods-title-btn">
            <view class="order-btn" @click="handelOperate('0')" style=" padding: 6px 12px;">修改可售库存</view>
            <view class="order-btn" @click="handelOperate('1')">清零</view>
            <view class="order-btn" @click="handelOperate('2')">置满</view>
          </view>
        </view>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" :loading="loading" style="height: 100%">
            <view class="form-container">
              <uni-table border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th align="left">商品</uni-th>
                  <uni-th align="left">商品名称</uni-th>
                  <uni-th align="left">规格</uni-th>
                  <uni-th align="left"><text class="start">* </text>可售库存（件）</uni-th>
                  <uni-th align="left">操作</uni-th>
                </uni-tr>
                <uni-tr v-for="(row, rIndex) in tableData" :key="rIndex">
                  <uni-td>
                    <image :src="row.mainImage" mode="widthFix" style="height: 32px;width:32px"></image>
                  </uni-td>
                  <uni-td>
                    <text>{{row.name}}</text>
                  </uni-td>
                  <uni-td>
                    <text>{{row.specComboDesc}}</text>
                  </uni-td>

                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="number" clearable v-model="row.stock"
                      v-if="row.stock!='不限量'">

                    </uni-easyinput>
                    <uni-easyinput placeholder="请输入" type="text" @input="handleStockInput(row)" clearable
                      v-model="row.stock" v-if="row.stock=='不限量'">

                    </uni-easyinput>
                  </uni-td>
                  <uni-td>
                    <view class="operation-btns">
                      <view class="btn" @click.stop="handelChang(row,0)">
                        置满
                      </view>
                      <view class="btn" @click.stop="handelChang(row,1)">
                        清零
                      </view>

                    </view>
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>
          </scroll-view>
        </view>
        <customPopup v-if="showPopup" :showPopup="showPopup" :typePopup="typePopup" :titPopup="titPopup"
          :infoPopup="infoPopup" :textPopup="textPopup" @cancelPopup="cancelPopup" @surePopup="surePopup"
          inputType='number' />
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>
<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import
  customPopup
  from '@/components/customPopup/index.vue';
  import {
    inventoryPage,
    updateInventory,
  } from '@/requests/apis/products'
  import
  addPopup
  from '@/components/addPopup/index.vue'
  let tableData = ref([])
  let loading = ref(true)
  let showPopup = ref(false);
  let titPopup = ref("");
  let typePopup = ref("");
  let infoPopup = ref("");
  let textPopup = ref(false)
  onLoad(async (e) => {
    loading.value = true
    if (e.spuIds) {
      let spuIds = e.spuIds.split(",")
      let res = await inventoryPage({
        spuIds,
        page: 1,
        limit: 999
      })
      console.log(res.Result)
      const records = res.Result?.records || [];
      tableData.value = records.map(item => {
        const stockNum = Number(item.stock);
        return {
          ...item,
          stock: stockNum === 99999 ? '不限量' : item.stock
        };
      });
      loading.value = false
    }
  })
  const handelOperate = (type) => {
    showPopup.value = true;
    if (type == '0') {
      textPopup.value = false
      titPopup.value = "批量改库存"
      infoPopup.value = '请输入调整后库存'
    } else if (type == '1') {
      textPopup.value = true
      titPopup.value = "批量清零"
      infoPopup.value = '剩余库存变为0，商品或规格会显示售罄。'
    } else {
      textPopup.value = true
      titPopup.value = "批量置满"
      infoPopup.value = '已配置最大库存商品，将按照最大库存置满商品库存。'
    }
    typePopup.value = type
  }
  // 弹窗取消
  const cancelPopup = () => {
    showPopup.value = false;
  };

  // 弹窗确认
  const surePopup = (type, modelValue) => {
    let _modelValue = Number(modelValue);
    showPopup.value = false;
    const fixDecimal = (num) => {
      return Math.round(num * 100) / 100;
    };

    if (type === "0") {
      tableData.value.forEach((row) => {
        row.stock = fixDecimal(_modelValue);
      });
    } else if (type === "1") {
      tableData.value.forEach((row) => {
        row.stock = 0;
      });
    } else {
      tableData.value.forEach((row) => {
        row.stock = row.targetStock == 99999 ? "不限量" : row.targetStock

      });
    }
  };
  const handelChang = (item, type) => {
    if (type == 0) {
      item.stock = item.targetStock == 99999 ? "不限量" : item.targetStock
    } else if (type == 1) {
      item.stock = 0
    }
  }

  const handleStockInput = (row) => {
    // 如果不是'不限量'，强制转为数字（避免输入非数字字符）
    if (row.stock !== '不限量') {
      // 移除所有非数字字符
      row.stock = row.stock.toString().replace(/[^0-9]/g, '');
      // 为空时置0（可选，根据业务需求调整）
      if (row.stock === '') {
        row.stock = ''; // 或 row.stock = 0;
      }
    }
  };
  const submit = async () => {
 const integerReg = /^\d+$/;
    let formData = JSON.parse(JSON.stringify(tableData.value))
    for (let i = 0; i < formData.length; i++) {
      const item = formData[i];

      // 处理“不限量”的情况
      if (item.stock === '不限量') {
        item.stock = 99999;
        item.limited = 0;
      } else {
        item.limited = 1;

        // 1. 验证库存是否为空或非数字
        if (item.stock === null || item.stock === '' || isNaN(Number(item.stock))) {
          uni.showToast({
            title: `请输入可售库存`,
            icon: 'none',
            duration: 2000,
          });
          return;
        }

        // 3. 验证是否为整数（非“不限量”时必须是整数）
        if (!integerReg.test(item.stock)) {
          uni.showToast({
            title: `可售库存必须为整数`,
            icon: 'none',
            duration: 2000,
          });
          return;
        }
        // 2. 转换为数字类型（处理字符串形式的数字）
        const stockNum = Number(item.stock);
        // 4. 最终赋值为整数（确保类型正确）
        item.stock = stockNum;
      }
    }
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    try {
      const res = await updateInventory({
        configDtoList: formData
      })
      console.log(res, 'resres')
      uni.hideLoading()
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 800)
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  :deep(.u-input) {
    background: #fff !important;
  }

  .form-container {
    padding: 0 20px;
    box-sizing: border-box;
  }

  .goods-container {
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;

    .operation-btns {
      display: flex;
      gap: 8rpx;

      .btn {
        font-weight: 400;
        font-size: 14px;
        color: #0F90FD;
      }
    }

    .goods-title {
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      align-items: center;

      text {
        font-weight: 500;
        font-size: 14px;
        color: #333333;
      }

      .goods-title-btn {
        display: flex;

        .order-btn {
          border-radius: 100px;
          border: 1px solid rgba(15, 144, 253, 0.8);
          color: #309FFD;
          font-weight: 500;
          font-size: 14px;
          padding: 6px 20px;
          box-sizing: border-box;
          margin-right: 10px;
        }
      }
    }
  }
</style>
